<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions" @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-input v-model="query.params.authName" placeholder="自定义菜单名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-has="'ADJUST_ORDER_OF_ORGAN'" type="primary" icon="el-icon-s-tools" size="mini" @click="adjustAuthorityOrder">菜单整理</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row row-key="id">
        <el-table-column label="自定义菜单名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.authName }}
          </template>
        </el-table-column>
        <el-table-column label="图标" width="110">
          <template slot-scope="scope">
            {{ scope.row.icon }}
          </template>
        </el-table-column>
        <el-table-column label="关联权限" width="110">
          <template slot-scope="scope">
            {{ scope.row.authId }}
          </template>
        </el-table-column>
        <el-table-column label="自定义父权限Id" width="140">
          <template slot-scope="scope">
            {{ scope.row.parentAuthId }}
          </template>
        </el-table-column>
        <el-table-column label="关联组织" width="110" prop="organId" :formatter="translateOrgan" />
        <el-table-column label="备注" width="110">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作" width="200">
          <template slot-scope="scope">
            <el-link style="cursor: pointer;" icon="el-icon-edit" type="warning" @click="handleEdit(scope.$index, scope.row)">
              {{ scope.row.isSet?'保存':"修改" }}
            </el-link>
            <el-divider direction="vertical"></el-divider>
            <el-link v-if="!scope.row.isSet" type="danger" class="el-icon-delete" style="cursor: pointer;" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 80, 120, 200, 500, 1000]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="主键" v-if="addForVisible">
            <el-input v-model="form.id" placeholder="主键" auto-complete="off" />
          </el-form-item>
          <el-form-item label="关联权限">
            <el-input v-model="form.authId" placeholder="关联权限" auto-complete="off" />
          </el-form-item>
          <el-form-item label="自定义父权限Id">
            <!-- <el-input v-model="form.parentAuthId" @focus="changeParentOrgan" placeholder="自定义父权限Id"  auto-complete="off"/> -->
            <el-cascader ref="authorityTree" v-model="form.parentAuthIds" placeholder="自定义父权限Id" :props="authorityProps" :options="authorityList" @change="getCheckedNodes" collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item label="关联组织">
            <el-input v-model="form.organId" placeholder="关联组织" auto-complete="off" />
          </el-form-item>
          <el-form-item label="所属组织路径">
            <el-input v-model="form.organPath" placeholder="所属组织路径" auto-complete="off" />
          </el-form-item>
          <el-form-item label="自定义菜单名称">
            <el-input v-model="form.authName" placeholder="自定义菜单名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="自定义图标">
            <el-input v-model="form.icon" placeholder="自定义图标" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogOrganAuthorityVisible">
        <el-tree ref="tree" :data="organAuthorityList" :default-expand-all="false" :props="defaultProps" :check-strictly="false" draggable node-key="id" highlight-current @node-drag-end="handleDragEnd" draggable :allow-drop="allowDrop" :allow-drag="allowDrag" />
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogOrganAuthorityVisible = false">取 消</el-button>
          <el-button v-has="'ADJUST_ORDER_OF_ORGAN'" type="primary" @click="adjustAuthorities">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit, getOrganAuthorities, doAdjust } from '@/api/organAuthority/'
import { querySubordinateOrgan } from '@/api/Organ'
import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'

export default {
  data() {
    return {
      list: [],
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogParentTreeVisible: false,
      dialogOrganAuthorityVisible: false,
      authorityList: [],
      organAuthorityList: [],
      adjustOrganAuthority: [],
      authorityProps: { // 配置项（必选）
        value: 'id',
        label: 'authName',
        children: 'children',
        checkStrictly: true,
        emitPath: false,
        expandTrigger: 'hover'
        // disabled:true
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      tenantOptions: [],
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      title: '组织',
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      defaultProps: {
        children: 'children',
        label: 'authName',
        url: 'url'
      },
      form: {
        id: '',
        authId: '',
        parentAuthId: '',
        parentAuthIds: [],
        organId: '',
        organPath: '',
        authName: '',
        isDeleted: '',
        icon: '',
        createBy: '',
        updateBy: '',
        createDate: '',
        updateDate: '',
        remark: ''
      },
      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑',
        adjust: '调整菜单'
      },
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          id: '' //主键
            ,
          authId: '' //关联权限
            ,
          parentAuthId: '' //自定义父权限Id
            ,
          organId: '' //关联组织
            ,
          organPath: '' //所属组织路径
            ,
          authName: '' //自定义菜单名称
            ,
          isDeleted: '' //已删
            ,
          icon: '' //自定义图标
            ,
          createBy: '' //生成者
            ,
          updateBy: '' //更新者
            ,
          createDate: '' //生成日期
            ,
          updateDate: '' //更新日期
            ,
          remark: '' //备注
        },
        currentPage: 1,
        pageSize: 10,
        total: 0,
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }],
        value: ''
      }
    }
  },
  created() {
    let that = this
    this.initOrganTree(() => {
      that.setOrganQueryType()
    }, getOrganPath())
    this.handleFiltTenant()
    this.initOrganFormTree()
    this.loadParentAuthoties()
    this.fetchData()
  },
  methods: {
    translateOrgan(row) {
      return translateOrganId2OrganName(row);
    },
    fetchData() {
      this.listLoading = true
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      getList(this.query.params, this.query.currentPage, this.query.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.query.pageSize = data.pageSize
        this.query.currentPage = data.currentPage
        this.list = data.entities
        debugger
        this.list = handleBuildTreeDataStruct(data.entities, 'authId', 'parentAuthId')
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.query.currentPage = 1
      this.query.pageSize = val
      this.fetchData()

    },
    handleCurrentChange(val) {
      this.query.currentPage = val
      this.fetchData()

    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.id = ''
      this.form.authId = ''
      this.form.parentAuthId = ''
      this.form.organId = ''
      this.form.organPath = ''
      this.form.authName = ''
      this.form.isDeleted = ''
      this.form.icon = ''
      this.form.createBy = ''
      this.form.updateBy = ''
      this.form.createDate = ''
      this.form.updateDate = ''
      this.form.remark = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)
      this.form.parentAuthIds = []
      this.form.id = row.id
      this.form.authId = row.authId
      this.form.parentAuthId = row.parentAuthId
      this.form.parentAuthIds.push(row.parentAuthId)
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.form.authName = row.authName
      this.form.isDeleted = row.isDeleted
      this.form.icon = row.icon
      this.form.createBy = row.createBy
      this.form.updateBy = row.updateBy
      this.form.createDate = row.createDate
      this.form.updateDate = row.updateDate
      this.form.remark = row.remark
      console.log(this.form)
      this.addForVisible = true
      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status == 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData();
          } else if (data.status == 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {
      doEdit(this.form).then(response => {
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData();
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    changeParentOrgan() {
      this.listLoading = true
      // this.dialogParentTreeVisible=true
      this.query.params.organId = getOrganId()
      getOrganAuthorities(this.query.params).then(response => {
        const responseData = response.data
        this.authorityList = handleBuildTreeDataStruct(responseData.data, 'authId', 'parentAuthId')
        this.listLoading = false
      })
    },
    loadParentAuthoties() {
      this.query.params.organId = getOrganId()
      getOrganAuthorities(this.query.params).then(response => {
        const responseData = response.data
        this.authorityList = handleBuildTreeDataStruct(responseData.data, 'authId', 'parentAuthId')
        this.listLoading = false
      })
    },
    getCheckedNodes(node) {
      let nodesInfo = this.$refs['authorityTree'].getCheckedNodes()
      console.log(nodesInfo)
      this.form.parentAuthId = nodesInfo[0].data.authId
    },
    initOrganTree(fn, filter, that) {
      debugger
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function(item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length === 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      debugger
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      if (this.props.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function(element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function() {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function() {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function() {
          this.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function() {
          this.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function(item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    adjustAuthorityOrder() {
      this.dialogOrganAuthorityVisible = true
      this.organAuthorityList = this.list
      // 编辑弹框标题
      this.dialogStatus = 'adjust'
      this.adjustOrganAuthority = []
    },
    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log('tree drag end: ', dropNode && dropNode.label, dropType);
      console.log('dropNode:', dropNode.data)
      console.log('draggingNode:', draggingNode.data)
      if ('inner' == dropType) {
        if (!draggingNode.data.originParentId) {
          draggingNode.data.originParentId = draggingNode.data.parentAuthId
        }
        draggingNode.data.parentAuthId = dropNode.data.authId
        this.adjustOrganAuthority.push(draggingNode.data)
      } else {
        if (!draggingNode.data.originParentId) {
          draggingNode.data.originParentId = draggingNode.data.parentAuthId
        }
        draggingNode.data.parentAuthId = dropNode.data.parentAuthId
        this.adjustOrganAuthority.push(draggingNode.data)
      }
    },
    allowDrop(draggingNode, dropNode, type) {
      if (dropNode.childNodes.length) {
        return true;
      } else {
        return false;
      }
    },
    allowDrag(draggingNode) {
      if (draggingNode.childNodes.length) {
        return true;
      } else {
        return false;
      }
    },
    adjustAuthorities() {
      if (this.adjustOrganAuthority.length) {
        this.$confirm('你确定这样调整菜单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          doAdjust(this.adjustOrganAuthority).then(response => {
            const responseData = response.data
            console.log(responseData)
            this.listLoading = false
            if (responseData) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.$message({
                type: 'danger',
                message: '操作失败'
              })
            }

          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作已取消'
          })
        })
      } else {
        this.$message({
          type: 'info',
          message: '您还没有操作哦！'
        })
      }


    }
  }
}

</script>
